<template>

  <div class="pop-item">
    <transition name="myfade">
      <div class='my-pop'
           v-if='popupVisible'>
        <div class='black-wrap '
             @click='popupVisible=false'></div>
        <div class="content-wrap ">
          <div class='content'>
            <div class='title'>
              订单结算
              <i class='iconfont icon-guanbi-copy'
                 @click='popupVisible=false'> </i>
            </div>
            <div class='goods-info'>
              <div>
                <img :src="buyItem.picture"
                     alt="产品图">
              </div>
              <div>
                <div>
                  {{buyItem.productName}}
                </div>
                <div>￥{{buyItem.price}}</div>
              </div>
            </div>
            <div class='discounted-price'
                 v-if='selectDiscount'
                 @click='popupVisibleTwo=true'>
              <div>

                {{selectDiscount&&selectDiscount.code_name=='贵宾价'?'贵宾价': ' 优惠'}}
                <div class='biaoshi'
                     v-if="selectDiscount&&selectDiscount.code_name!='贵宾价'">
                  {{selectDiscount.code_name=='随机立减'||selectDiscount.code_name=='贵宾价'?selectDiscount.code_name:'优惠劵'}}
                </div>

              </div>

              <div class=''>
                <span>
                  <img src="@/assets/icon-hg@2x.png"
                       v-if="selectDiscount&&selectDiscount.code_name=='贵宾价'"
                       alt=""> ￥{{selectDiscount.convert_money}}元
                </span>
                <i class='iconfont icon-qianjin'></i>
              </div>

            </div>
            <div class='discounted-price'>
              <span>
                实付
              </span>
              <div class=''>
                <b> ￥{{total()}}元</b>

              </div>
            </div>

          </div>
          <div class='btn-submit'>

            <mt-button type="primary"
                       :disabled='isDisableBuy'
                       @click.native='sumbit'
                       :class="'theme_'
                       +$store.state.styleColor"
                       size="large">{{isDisableBuy?'每日仅限购一桶':'确认'}} </mt-button>
          </div>
        </div>
      </div>
    </transition>
    <mt-popup v-model="popupVisibleTwo"
              v-if='popupVisibleTwo'
              position="bottom">
      <div class='picker-wrap'>

        <mt-picker :showToolbar="true"
                   :visibleItemCount="3"
                   :slots="slots"
                   value-key="code_name"
                   @change="onValuesChange">
          <div class="findTitle">
            <span @click='popupVisibleTwo=false'>取消</span>
            <!-- <span>确定</span> -->
          </div>

        </mt-picker>
      </div>
    </mt-popup>
    <transition name="fade">
      <div class='order-time animated slideInDown'
           v-if='$store.state.orderTime>0'>
        有未完成订单，请手动取消或者等待
        {{$store.state.orderTime}}s再次购买
      </div>
    </transition>
  </div>

</template>

<script>

import { findDiscountUserMoney, findUserCode, wxPay, zfbzf, findOrderPurchaseLimitation, findVipProduct } from '@/api'
import { init, savePay } from '@/common/js/globalJs.js'
import { mapGetters, mapActions } from 'vuex'
import { Toast } from 'mint-ui';
export default {
  props: {
    pop: '',
    buyItem: '',
    isDisableBuy: {
      type: Boolean,
      default: false
    },
    isActivity: {
      type: Boolean,
      default: false
    },

  },
  data () {
    return {
      popupVisible: false,
      popupVisibleTwo: false,
      popupVisibleTime: true,

      slots: [
        {
          flex: 1,
          values: [],
          defaultIndex: 0,
          className: 'slot1',
        }
      ],
      selectDiscount: '',
      selectChangeItem: ''
    }

  },

  watch: {
    $route (n, x) {
      if (x.name == 'home') {
        this.popupVisible = false;
        this.popupVisibleTwo = false;
      }

    },
    pop () {
      this.isDisableBuy = false;
      this.init();
    }
  }
  ,
  methods: {

    init () {
      //  限购-> vip特价 ->优惠券 -> 随机立减
      // 是否有随机立减  如果有 先访问findDiscountUserMoney 再访问findUserCode 如果没有  直接访问findUserCode
      this.selectDiscount = '';
      this.slots[0].values = [];
      this.loading.open('加载中...');

      let data = this.buyItem;
      let userInfo = this.getUserInfo();
      if (data.isLimit) {
        //满足限购条件

        this._getLimit();

      } else if (userInfo.clientId) {
        //满足VIP贵宾条件
        this._getvVipCoupon(userInfo, data);
      } else {
        //满足随机立减
        if (this.isActivity) {
          this._getRandomMoeny();
        }
        //满足优惠劵条件
        this._getCommonCoupon();

      }

      this.loading.close();
    },
    /**用户购买是否有限购 */
    _getLimit () {
      findOrderPurchaseLimitation().then(res => {
        this.isDisableBuy = res.tag == 1 ? false : true;
        this.endShouchang();
      })
    },
    /**获取VIP优惠 */
    _getvVipCoupon (userInfo, data) {
      findVipProduct({
        clientId: userInfo.clientId,
        productId: data.productId
      }).then(res => {
        //是贵宾  则去贵宾价格 否则走随机立减和优惠劵获取接口
        if (res.vipPrice.tag == 1) {
          let subtract = {
            code_name: '贵宾价',
            convert_money: res.vipPrice.vipPrice,
            randomDiscountId: res.vipPrice.gohVipPriceRecordId,
            randomDiscountMoney: res.vipPrice.vipPrice,
            randomActivityId: res.vipPrice.eventId
          }
          this.slots[0].values.push(subtract);
          this.endShouchang();
        } else {
          //满足随机立减
          if (this.isActivity) {
            this._getRandomMoeny();
          }
          this._getCommonCoupon();
        }
      });
    },
    /**普通优惠劵 */
    _getCommonCoupon () {
      findUserCode({ "isAll": false }).then(res => {
        if (res.code.length) {
          let code = res.code;
          for (var i = 0, len = code.length; i < len; i++) {
            // 筛选 相同pid 的才让他选择
            if (code[i].pid == this.buyItem.productId) {
              this.slots[0].values.push(code[i]);
            }
          }

        }
        this.endShouchang();

      })
    },
    /**获取随机立减 */
    _getRandomMoeny () {
      findDiscountUserMoney().then(res => {

        if (res.discountMoney) {
          let d = res.discountMoney;
          let money = res.discountMoney.randomDiscountMoney
          if (money > 0) {
            var subtract = {
              "code_name": '随机立减',
              "convert_money": money,
              "randomDiscountId": d.randomDiscountId,
              "randomDiscountMoney": money,
              "randomActivityId": d.randomActivityId
            }
            this.slots[0].values.push(subtract);
          }
          this.endShouchang();
        }
      })
    },
    /**
        * 支付（微信和支付宝）
        * @param  {[int]}      boxNum                  柜门序号(1-28)
        * @param  {[int]}      productId               商品ID
        * @param  {[double]}   price                   商品价格金额
        * @param  {[int]}      mcId                    货柜ID
        * @param  {[double]}   finalMoney              实际金额
        * @param  {[int]}      codeTypeId              代金券方案ID
        * @param  {[string]}   codeNo                  优惠券金额
        * @param  {[int]}      randomDiscountId        随机立减ID
        * @param  {[int]}      randomActivityId        随机立减活动ID
        * @param  {[double]}   randomDiscountMoney     随机立减金额
        * @param  {[int]}      gohVipPriceRecordId     贵宾商品Id
        * @param  {[int]}      clientId                用户clientId
        * 
        */
    sumbit () {
      let item = this.buyItem;
      let disc = this.selectDiscount
      let userInfo = this.getUserInfo();


      localStorage.setItem("payDoor", item.doorIndex);
      let params;


      //没有优惠劵
      if (!disc) {
        params = {
          "boxNum": item.doorIndex,
          "productId": item.productId,
          "price": this.total(),
          "finalMoney": this.total(),
          "randomDiscountMoney": 0,
        }
      }//贵宾价
      else if (userInfo && userInfo.clientId > 0 && disc.code_name == '贵宾价') {
        params = {
          "boxNum": item.doorIndex,
          "productId": item.productId,
          "price": this.total(),
          "finalMoney": 0,
          "randomDiscountMoney": 0,
          "gohVipPriceRecordId": disc.randomDiscountId,
          "clientId": userInfo.clientId
        }
      } //有优惠劵
      else {


        params = {
          "boxNum": item.doorIndex,
          "productId": item.productId,
          "price": item.price,
          "finalMoney": this.total(),
          "codeTypeId": disc ? disc.TYPE_ID : null,
          "codeNo": disc ? disc.code_no : null,
          "randomDiscountId": disc ? disc.randomDiscountId : 0,
          "randomActivityId": disc ? disc.randomActivityId : 0,
          "randomDiscountMoney": disc ? (disc.randomDiscountMoney ? disc.randomDiscountMoney : 0) : 0,
        }
      }


      this.loading.open('加载中...');
      if (/MicroMessenger/.test(window.navigator.userAgent)) {


        wxPay(params).then(res => {
          this.loading.close();
          localStorage.setItem("payOrderId", res.orderId)
          localStorage.setItem("payOrderNo", res.orderNo)
          if (res.code != "E00000") {
            let step = res.message.slice(res.message.lastIndexOf('|') + 1);

            if (step > 0) {
              this.startTimeCount(step);
              return
            }
            Toast({
              message: res.message,
              position: 'middle',
              duration: 5000
            });
          } else {
            savePay(res.appId, res.timeStamp, res.nonceStr, res.package, res.paySign, item.doorIndex).then(res => {
              console.log('支付回调', res);
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                this.$router.push({ path: "/paySuccess" })
              }
            });
          }

          this.popupVisible = false;
          this.popupVisibleTwo = false;

        })
      } else if (/AlipayClient/.test(window.navigator.userAgent)) {
        zfbzf(params).then(res => {
          this.loading.close();
          if (res.code == "E00001") {
            let step = res.message.slice(res.message.lastIndexOf('|') + 1);
            if (step > 0) {
              this.startTimeCount(step);
              return
            }
            Toast({
              message: res.message,
              position: 'middle',
              duration: 5000
            });
          } else {
            console.log(res);

            localStorage.setItem("payOrderId", res.orderId)
            localStorage.setItem("payOrderNo", res.orderNo)
            const div = document.createElement('div');
            div.innerHTML = res.pay;
            document.body.appendChild(div);
            this.$nextTick(() => {
              document.forms[0].submit();
            })
          }
        })
        // index#/paySuccess

      }

    },
    /**数据都请求完后才显示弹出 ，并设置优惠劵默认值 */
    endShouchang () {
      this.loading.close();
      this.selectDiscount = this.slots[0].values[0]
      this.popupVisible = true
    },
    /**优惠劵发生改变 */
    onValuesChange (picker, values) {
      this.selectChangeItem = values[0]
      this.selectDiscount = values[0]
    },
    total () {
      let selectDiscount = this.selectDiscount;
      let buyItem = this.buyItem;
      if (selectDiscount && selectDiscount.code_name == "贵宾价") {
        return selectDiscount.convert_money;
      } else if (buyItem) {
        //减去优惠的金额
        let price = selectDiscount && selectDiscount.convert_money ? (buyItem.price - selectDiscount.convert_money).toFixed(2) : buyItem.price.toFixed(2)
        return price > 0 ? price : 0
      }
    },
    ...mapGetters({
      getUserInfo: 'getUserInfo'
    }),
    ...mapActions({
      startTimeCount: "setOrderTime"
    })
  },
};
</script>
<style lang="scss">
@import "@/common/scss/mixin.scss";
.mint-popup {
  background: transparent;
}
.pop-item {
  .my-pop {
    @include fjc;
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: 30;
    height: calc(100% - 100px);
    height: calc(100% - 100px - env(safe-area-inset-bottom));
    .black-wrap {
      @include black-wrap-fixed;
      height: calc(100% - 100px);
      height: calc(100% - 100px - env(safe-area-inset-bottom));
    }
    .content-wrap {
      z-index: 10;
      border-radius: 16px;
      background: #fff;
      padding: 30px;
      padding-top: 0;
      width: 636px;
      box-sizing: border-box;
      .content {
        .title {
          position: relative;
          height: 88px;
          @include fjc;
          @include color111;
          font-size: 32px; /*px*/
          i {
            padding: 30px;
            position: absolute;
            right: -10px;
            top: 50%;
            transform: translate(0, -50%);
          }
        }
        > div {
          border-bottom: 2px dashed $color-border;
        }

        .goods-info {
          display: flex;
          padding: 25px 0;
          > div:first-child {
            width: 160px;
            padding: 0 30px;

            img {
              height: 160px;
            }
          }
          > div:last-child {
            flex: 1;
            display: flex;
            align-content: center;
            flex-flow: row wrap;

            > div {
              width: 100%;
              font-size: 28px;
              color: #111;
              text-align: left;
            }
            > div:last-child {
              font-size: 32px; /*px*/
              color: $color-sub-theme;
              margin-top: 16px;
            }
          }
        }
        .discounted-price {
          height: 88px;
          font-size: 28px; /*px*/
          @include fjc(center, space-between);
          @include color999;
          > div {
            display: flex;
            align-items: center;
            img {
              width: 40px;
            }
            .biaoshi {
              display: inline-flex;
              justify-content: center;
              align-items: center;
              font-size: 20px; /*px*/
              padding: 4px 8px;
              border: 2px solid #e24a4a;
              border-radius: 8px;
              color: #e24a4a;
              margin-left: 15px;
            }
            b {
              @include color111;
            }
            span {
              color: $color-sub-theme;
            }
          }
        }
      }
      .btn-submit {
        padding-top: 48px;
      }
    }
  }
}
.mint-popup-bottom {
  width: 100%;

  > .picker-wrap {
    background: #fff;
    padding-bottom: 100px; /*px*/
    padding-bottom: calc(env(safe-area-inset-bottom) + 100px); /*px*/
    .findTitle {
      height: 88px;
      @include fjc(center, space-between);
      font-size: 28px; /*px*/
      padding: 0 30px;
    }
  }
}
.order-time {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100px;
  z-index:40;
  background: rgba(0, 0, 0, 0.9);
  @include fjc;
  color: #fff;
  font-size: 26px; /*px*/
}

.myfade-enter-active,
.myfade-leave-active {
  transition: opacity 0.3s;
}
.myfade-enter, .myfade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
